#
# VARIABLES
# 
SRCDIR = src
OBJDIR = obj
BINDIR = bin

GRUB2SCRIPTPATH = /etc/grub.d/90_apoc

CCFLAGS = -I $(SRCDIR) -std=c++0x -g -nostdinc -Wall -static -fno-common -fno-exceptions -fno-stack-protector -fno-non-call-exceptions -fno-weak -fno-rtti -fno-builtin -c

X86_32_CCFLAGS = $(CCFLAGS) -m32 -D APOC_ARCH=APOC_ARCH_X86_32
X86_64_CCFLAGS = $(CCFLAGS) -m64 -D APOC_ARCH=APOC_ARCH_X86_64

LDFLAGS = -nostdlib

X86_32_LDFLAGS = $(LDFLAGS) -melf_i386
X86_64_LDFLAGS = $(LDFLAGS) -melf_x86_64

LD = ld
CC = gcc
OC = objcopy

#
# TARGETS
#
all: x86-32 x86-64
x86: x86-32
x86-32: $(BINDIR)/apoc-x86-32.img $(OBJDIR)/kernel-x86-32 $(OBJDIR)/mbrboot-x86-32
x86-64: $(BINDIR)/apoc-x86-64.img $(OBJDIR)/kernel-x86-64 $(OBJDIR)/mbrboot-x86-64

$(BINDIR)/apoc-x86-32.img: $(OBJDIR)/kernel-x86-32 $(OBJDIR)/mbrboot-x86-32
	@echo + $@
	@diskmbr -create $(OBJDIR)/mbrboot-x86-32 > $(OBJDIR)/mbr-x86-32
	@dd if=/dev/zero of=$@ count=200 > /dev/null 2>&1
	@dd if=$(OBJDIR)/mbr-x86-32 of=$@ count=1 conv=notrunc > /dev/null 2>&1
	@dd if=$(OBJDIR)/kernel-x86-32 of=$@ seek=1 conv=notrunc > /dev/null 2>&1

$(BINDIR)/apoc-x86-64.img: $(OBJDIR)/kernel-x86-64 $(OBJDIR)/mbrboot-x86-64
	@echo + $@
	@diskmbr -create $(OBJDIR)/mbrboot-x86-64 > $(OBJDIR)/mbr-x86-64
	@dd if=/dev/zero of=$@ count=200 > /dev/null 2>&1
	@dd if=$(OBJDIR)/mbr-x86-64 of=$@ count=1 conv=notrunc > /dev/null 2>&1
	@dd if=$(OBJDIR)/kernel-x86-64 of=$@ seek=1 conv=notrunc > /dev/null 2>&1

clean:
	@rm -f $(OBJDIR)/* $(BINDIR)/*

clean-all: clean all

debug-x86-32: x86-32
	@qemu -k en-us -hda $(BINDIR)/apoc-x86-32.img -serial stdio

debug-x86-32-gdb: x86-32
	@qemu -k en-us -hda $(BINDIR)/apoc-x86-32.img -serial stdio -s -S

debug-x86-64: x86-64
	@qemu-system-x86_64 -k en-us -hda $(BINDIR)/apoc-x86-64.img -serial stdio

debug-x86-64-gdb: x86-64
	@qemu-system-x86_64 -k en-us -hda $(BINDIR)/apoc-x86-64.img -serial stdio -s -S

install-x86-32-grub2: $(BINDIR)/apoc-x86-32.img
	@echo "APOC partition path:"; \
	read device_path; \
	echo Installing APOC to $$device_path...; \
	dd if=$(BINDIR)/apoc-x86-32.img of=$$device_path; \
	echo exec\ tail\ -n\ +2\ '$$''0' > $(GRUB2SCRIPTPATH) && echo "menuentry \"APOC\" {" >> $(GRUB2SCRIPTPATH) && echo "set root='(hd0,2)'" >> $(GRUB2SCRIPTPATH) && echo "chainloader (hd0,2)+1" >> $(GRUB2SCRIPTPATH) && echo "}" >> $(GRUB2SCRIPTPATH)
	@chmod +x $(GRUB2SCRIPTPATH)
	@echo "Updating GRUB..."
	@update-grub

install-x86-64-grub2: $(BINDIR)/apoc-x86-64.img
	@echo "APOC partition path:"; \
	read device_path; \
	echo Installing APOC to $$device_path...; \
	dd if=$(BINDIR)/apoc-x86-64.img of=$$device_path; \
	echo exec\ tail\ -n\ +2\ '$$''0' > $(GRUB2SCRIPTPATH) && echo "menuentry \"APOC\" {" >> $(GRUB2SCRIPTPATH) && echo "set root='(hd0,2)'" >> $(GRUB2SCRIPTPATH) && echo "chainloader (hd0,2)+1" >> $(GRUB2SCRIPTPATH) && echo "}" >> $(GRUB2SCRIPTPATH)
	@chmod +x $(GRUB2SCRIPTPATH)
	@echo "Updating GRUB..."
	@update-grub

include src/Makefrag
include src/boot/Makefrag
